package com.cdty.chess.service.impl;

import com.cdty.chess.model.BetCountInfo;
import com.cdty.chess.model.Room;
import com.cdty.chess.service.RoomService;
import com.cdty.chess.vo.RoomVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ThreadLocalRandom;

@Service
public class RoomServiceImpl implements RoomService {

    @Autowired
    NamedParameterJdbcTemplate template;

    @Override
    @Transactional
    public String addRoom(Room room) {
        try {
            // 1新增房间
            String roomsql = """
                    insert into 
                        room( id,rname, create_time, is_del )
                        values(  :id,:rname, now(), false )
                    """;
            //生成6位数房间号
            int randomNumber = ThreadLocalRandom.current().nextInt(100000, 999999);
            //获取房间号uuid()
            String uidsql = " select uuid() uid";
            Map<String, Object> uidobj = template.queryForMap(uidsql, new MapSqlParameterSource());
            String rid = uidobj.get("uid").toString();
            int i = template.update(roomsql, new MapSqlParameterSource("rname", randomNumber)
                    .addValue("uid", room.getUid())
                    .addValue("id", rid));
            // 2新增对局
            BetCountInfo info = new BetCountInfo();
            info.setRid(rid);
            info.setIs_bet("1"); //未开盘
            String bCountsql = """
                    insert into
                    bet_count_info(
                    create_time,rid,is_bet
                    )values(
                    now(),:rid,'1'
                    )
                    """;
            template.update(bCountsql, new MapSqlParameterSource("rid", rid));
            return "success";
        } catch (Exception e) {
            e.printStackTrace();
            return "error";

        }
    }

    @Override
    public String updateRoom(String rid) {
        //删除前判断是否为开盘或者开盘结束
        String sql = """
                    select bci.* from room rm inner join bet_count_info bci 
                    on rm.id = bci.rid
                    where rm.id = :rid and (rci.is_bet ='2' or  rci.is_bet ='3')
                """;
        List<BetCountInfo> list = template.query(sql, new BeanPropertyRowMapper<BetCountInfo>(BetCountInfo.class));
        if (list.size() > 0) {
            return "存在未结束的对局,请等待开奖结束";
        } else {
            String updatsql = """
                        update room set is_del = true where id = :rid
                    """;

            int cou = this.template.update(updatsql, new MapSqlParameterSource("rid", rid));
            if (cou == 1) {
                return "删除成功";
            } else {
                return "删除失败,该房号不存在";
            }
        }
    }

    @Override
    public List<RoomVo> queryRoom(String rname) {
        String sql = """
                    SELECT r.*,cu.uname from room r 
                    left join cuser cu on cu.uid = r.uid
                    where is_del = 0
                
                """;
        MapSqlParameterSource param = new MapSqlParameterSource();

        if (StringUtils.hasText(rname)) {
            sql += " and r.rname = :rname";
            param.addValue("rname", rname);
        }

        List<RoomVo> list = template.query(sql, param, new BeanPropertyRowMapper<RoomVo>(RoomVo.class));
        return list;
    }

    @Override
    public String update(String uid, String rid) {
        //更新room
        if(StringUtils.hasText(uid)){
            String sql = """
                    update room set uid = :uid where id = :rid
                """;
            MapSqlParameterSource params = new MapSqlParameterSource("rid", rid).addValue("uid", uid);
            int i = template.update(sql, params);
            System.out.println(i);

        }else {
            String sql = """
                    update room set uid = null where rid = :rid
                """;
            MapSqlParameterSource params = new MapSqlParameterSource("rid", rid);
            int i = template.update(sql, params);
            System.out.println(i);
        }

        return "success";
    }
}
